"use strict";
const axios = require("axios");
const urlJoin = require("url-join");
const semver = require("semver");

const verAIsLaterThenVerB = (verA, verB) => semver.compare(verA, verB) > 0;

const sortVersions = (versions) => versions.sort((a, b) => semver.compare(b, a));

const getSemverVersions = (baseVer, versions) =>
	sortVersions(versions
		.filter(item => semver.satisfies(item, `>${baseVer}`)));

const getNpmSemverVersion = async (baseVer, npmName, registry) => {
	const versions = await getNpmVersions(npmName, registry);
	if (versions) {
		const semverVersions = getSemverVersions(baseVer, versions);
		if (semverVersions.length) {
			return semverVersions[0];
		}
		return null;
	}
	return null;
};

const getNpmVersions = (npmName, registry) => {
	if (!npmName) {
		return null;
	}
	const registryUrl = registry || getDefaultRegistry();
	const npmInfoUrl = urlJoin(registryUrl, npmName);

	return axios.get(npmInfoUrl).then((response) => {
		if (response.status === 200) {
			return Object.keys(response.data.versions);
			// return ["1.0.4", "0.0.4", "2.0.4", "0.0.3",];
		}
		return null;
	}).catch((err) => {
		return Promise.reject(err);
	});
};

const getNpmLatestVersion = async (...args) => {
	const res = await getNpmVersions.apply(null, args);
	if (Array.isArray(res) && res.length) {
		return sortVersions(res)[0];
	}
	return null;
};
const getDefaultRegistry = (isOriginal = false) => {
	return `https://registry.npmjs.com/`;
};

module.exports = {
	getNpmSemverVersion,
	getDefaultRegistry,
	getNpmLatestVersion,
	verAIsLaterThenVerB
};
